package cz.muni.fi.pa165.sme.web.security;

import org.apache.wicket.Component;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;

/** @author forman */
public class Authorizer {

	public static void authorizeAdmin(Component component) {
		boolean enabled = false;
		if(isAuthenticationSet()) {
			for (GrantedAuthority authority : SecurityContextHolder.getContext().getAuthentication().getAuthorities()) {
				if (authority.getAuthority().equals("ADMIN")) {
					enabled = true;
				}
			}
		}
		component.setEnabled(enabled);
		component.setVisible(enabled);
	}

	public static void authorizeUser(Component component) {
		boolean enabled = false;
		if(isAuthenticationSet()) {
			for (GrantedAuthority authority : SecurityContextHolder.getContext().getAuthentication().getAuthorities()) {
				if (authority.getAuthority().equals("USER")) {
					enabled = true;
				}
			}
		}
		component.setEnabled(enabled);
		component.setVisible(enabled);
	}

	public static void authorizeCommon(Component component) {
		boolean enabled = true;
		if(isAuthenticationSet() && !SecurityContextHolder.getContext().getAuthentication().getAuthorities().isEmpty()) {
			enabled = false;
		}
		component.setEnabled(enabled);
		component.setVisible(enabled);
	}

	public static boolean isAdminLogged() {
		boolean result = false;
		if(isAuthenticationSet()) {
			for (GrantedAuthority authority : SecurityContextHolder.getContext().getAuthentication().getAuthorities()) {
				if (authority.getAuthority().equals("ADMIN")) {
					result = true;
				}
			}
		}
		return result;
	}

	private static boolean isAuthenticationSet() {
		return SecurityContextHolder.getContext().getAuthentication() != null;
	}
}
